package com.qqtech.qquan.community.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.qqtech.core.common.cache.Cache;
import com.qqtech.core.common.util.SettingCfgUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.community.dao.CommunitySysDictDao;
import com.qqtech.qquan.community.model.CommunitySysDict;

@Service
public class CommunitySysDictServiceImpl extends BaseServiceImpl<CommunitySysDict> implements CommunitySysDictService,
		Cache<String, List<CommunitySysDict>> {
	public static final Logger log = LoggerFactory.getLogger(CommunitySysDictServiceImpl.class);

	@Resource
	private CommunitySysDictDao communitySysDictDao;

	@Override
	protected BaseDao<CommunitySysDict> getBaseDao() {
		return communitySysDictDao;
	}

	private LoadingCache<String, List<CommunitySysDict>> caches = CacheBuilder
			.newBuilder()
			.recordStats()
			.expireAfterWrite(SettingCfgUtil.getConfigHelper("qquan-cfg.properties").getIntValue("paramcache.expire.mins"),
					TimeUnit.MINUTES).build(new CacheLoader<String, List<CommunitySysDict>>() {
				public List<CommunitySysDict> load(String dictType) {
					CommunitySysDict communitySysDict = new CommunitySysDict();
					communitySysDict.setType(dictType);
					List<CommunitySysDict> CommunitySysDictList = communitySysDictDao.queryList(communitySysDict);
					if (CommunitySysDictList != null) {
						return CommunitySysDictList;
					}
					return Lists.newArrayList();
				}
			});

	public String dictValue(String dictType, String dictKey) {
		if (Strings.isNullOrEmpty(dictType) || Strings.isNullOrEmpty(dictKey)) {
			return "";
		}
		List<CommunitySysDict> dicts = caches.getUnchecked(dictType);
		for (CommunitySysDict dict : dicts) {
			if (dictKey.equals(dict.getCode())) {
				return dict.getName();
			}
		}
		return "";
	}

	@Override
	public List<CommunitySysDict> get(String dictType) {
		return caches.getUnchecked(dictType);
	}

	@Override
	public void clear(String dictType) {
		caches.invalidate(dictType);
	}

	@Override
	public void clearAll() {
		caches.invalidateAll();
	}

}